package com.hy.net.manager

import android.util.Log
import com.hy.net.error.ERROR
import com.hy.net.error.NoNetWorkException
import com.hy.net.helper.HyAppHelper
import com.hy.net.interceptor.CookiesInterceptor
import com.hy.net.interceptor.HeaderInterceptor
import com.hy.net.interceptor.PublicParameterInterceptor
import com.hy.net.interceptor.TimeoutInterceptor
import com.hy.net.utils.HyNetworkUtil
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 * @Description:
 * @Author: wdk
 * @CreateTime: 2024/5/27 22:29
 */
abstract class HyRetrofitFactory : HyRetrofitCreate {
    companion object{
        private const val TAG = "HyRetrofitFactory"
    }


    private var mRetrofit: Retrofit? = null

    /**
     * 获取baseUrl，由子类实现
     */
    abstract fun getBaseUrl(): String

    /**
     * 链接超时，默认30秒
     */
    fun getConnectTimeout(): Long {
        return 30L
    }

    fun getWriteTimeout(): Long {
        return 30L
    }

    fun getReadTimeout(): Long {
        return 30L
    }


    override fun createRetrofit(): Retrofit {
        return mRetrofit ?: let {
            val retrofit = Retrofit.Builder()
                .client(initOkHttpClient())
                .baseUrl(getBaseUrl())
                .addConverterFactory(GsonConverterFactory.create())
                .build()
            mRetrofit = retrofit
            retrofit
        }
    }

    override fun getInstance(): Retrofit {
        return createRetrofit()
    }


    /**
     * 初始化OkHttp
     */
    override fun initOkHttpClient(): OkHttpClient {
        val build = OkHttpClient.Builder()
            .connectTimeout(getConnectTimeout(), TimeUnit.SECONDS)
            .writeTimeout(getWriteTimeout(), TimeUnit.SECONDS)
            .readTimeout(getReadTimeout(), TimeUnit.SECONDS)
        // 添加参数拦截器
//        val interceptors = mutableListOf<Interceptor>()
        build.apply {
            addInterceptor(PublicParameterInterceptor())
            addInterceptor(TimeoutInterceptor())
//            addInterceptor(CookiesInterceptor())
            addInterceptor(HeaderInterceptor())
        }

        //日志拦截器
        val logInterceptor = HttpLoggingInterceptor { message: String ->
            Log.i(TAG, "data:$message")
        }
        if (HyAppHelper.isDebug()) {
            logInterceptor.level = HttpLoggingInterceptor.Level.BODY
        } else {
            logInterceptor.level = HttpLoggingInterceptor.Level.BASIC
        }
        build.addInterceptor(logInterceptor)
        //网络状态拦截
        build.addInterceptor(object : Interceptor {
            override fun intercept(chain: Interceptor.Chain): Response {
                if (HyNetworkUtil.isConnected(HyAppHelper.getApplication())) {
                    Log.i(TAG, "network connect true")
                    val request = chain.request()
                    return chain.proceed(request)
                } else {
                    throw NoNetWorkException(ERROR.NETWORD_ERROR)
                }
            }
        })
        return build.build()
    }

    /**
     * 获取 apiService
     */
    fun <T> create(apiService: Class<T>): T {
        return getInstance().create(apiService)
    }
}